<!-- subpkg_consult/room/index.vue -->
<script lang="ts" setup>
  import { getOrderDetailAPI, uploadAPI } from '@/api'
  import { GlobalVariable } from '@/constants'
  import { useTokenStore } from '@/store/token'
  import type { OrderDetailData } from '@/types/consult'
  import type { MsgData, MsgItem } from '@/types/room'
  import { io } from '@hyoga/uni-socket.io'
  import dayjs from 'dayjs'
  import relativeTime from 'dayjs/plugin/relativeTime'
  import 'dayjs/locale/zh-cn'
  dayjs.extend(relativeTime) // 扩展时间
  // 切换dayjs的语言包
  dayjs.locale('zh-cn')

  import { nextTick, onMounted, ref } from 'vue'
  import { audioManager } from '@/utils/AudioManager'
  const store = useTokenStore()
  const props = defineProps<{
    orderId: string
    payResult: string
    type: string
  }>()
  const socket = io(GlobalVariable.BASE_URL, {
    auth: {
      token: `Bearer ${store.getToken()}`,
    },
    query: {
      orderId: props.orderId, // 和服务器建立链接关系传入我是哪个订单问诊
    },
    transports: ['websocket', 'polling'], // 和后端进行即时通讯的格式
    timeout: 5000,
  })

  const orderDetail = ref<OrderDetailData>()
  const getOrderDetail = async () => {
    orderDetail.value = await getOrderDetailAPI(props.orderId)
    console.log(orderDetail.value)
  }
  getOrderDetail()

  // 聊天消息列表
  const chatMsgList = ref<MsgItem[]>([])

  // 定义输入框的数据
  const inputValue = ref('')
  socket.on('connect', () => {
    console.log('和服务器建立链接成功')
  })
  // 接收历史消息
  socket.on('chatMsgList', (data: MsgData) => {
    if (data.code === GlobalVariable.SUCCESS_CODE) {
      // 此时请求成功
      // 数据结构为 [{  items: [ {}] }, {  items: [ {}] }, {  items: [ {}] }]
      data.data?.forEach((obj) => {
        chatMsgList.value.push(
          {
            msgType: 31,
            msg: {
              content: dayjs(obj.createTime).fromNow(), // 消息内容是时间
            },
          },
          ...obj.items!
        )
      })
      nextTick(() => {
        // 滚动到具体的消息的内容
        // 内容绑定给scroll-view的组件的scroll-into-view
        sp.value = `item-${chatMsgList.value.length - 1}` // 最后一个元素的id
      })
    }
  })
  const sp = ref('') // 滚动的具体位置

  // 接收新消息
  socket.on('receiveChatMsg', (data: MsgItem) => {
    console.log(data)
    chatMsgList.value.push(data)
    if (data.from !== store.getUserId()) {
      // 如果消息不是当前用户发送的 则播放音频
      audioManager.play('/static/message.mp3')
    }
    // 需要等到上面的数据更新完成 才进行滚动
    nextTick(() => {
      // 滚动到具体的消息的内容
      // 内容绑定给scroll-view的组件的scroll-into-view
      sp.value = `item-${chatMsgList.value.length - 1}` // 最后一个元素的id
    })
  })
  // 状态变更的消息
  socket.on('statusChange', () => {
    getOrderDetail()
  })
  socket.on('error', () => {
    console.log('出现错误')
  })
  socket.on('disconnect', () => {
    console.log('和服务断开')
  })
  // 发送消息
  const sendMsg = () => {
    // 如果输入框为空 则不发送
    if (inputValue.value.trim() === '') {
      uni.showToast({
        title: '请输入消息',
        icon: 'none',
      })
      return
    }

    socket.emit('sendChatMsg', {
      from: store.getUserId(), // 当前谁的发消息 并不是用患者的id作为通知 用当前用户的消息
      to: orderDetail.value?.docInfo?.id,
      msg: {
        content: inputValue.value,
      },
      msgType: 1, // 1: 文字消息 4: 图片消息
    })
    inputValue.value = ''
  }
  // 上传图片
  const uploadImage = () => {
    // 保证当前的orderDetail.value?.status 为3
    if (orderDetail.value?.status === 3) {
      // 只有在咨询中的时候才可以发图片
      // 上传图片 选择图片
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: async (res) => {
          const filePath = res.tempFilePaths[0] // 获取图片临时路径
          // 上传图片
          const result = await uploadAPI(filePath)
          // 发送图片消息
          socket.emit('sendChatMsg', {
            from: store.getUserId(), // 当前谁的发消息 并不是用患者的id作为通知 用当前用户的消息
            to: orderDetail.value?.docInfo?.id,
            msg: {
              picture: result,
            },
            msgType: 4, // 1: 文字消息 4: 图片消息
          })
        },
      })
    }
  }
</script>

<template>
  <view class="room-page">
    <custom-status
      :status="orderDetail?.status"
      :statusValue="orderDetail?.statusValue"
      :countdown="orderDetail?.countdown"
    />
    <scroll-view
      :scroll-into-view="sp"
      refresher-enabled
      refresher-background="#f2f2f2"
      scroll-y
      style="flex: 1; overflow: hidden"
    >
      <!-- <view class="message-container"> -->
      <!-- 此处将来填充更多代码... -->
      <view v-for="(item, index) in chatMsgList" :id="`item-${index}`" :key="item.id">
        <!-- 当msgType 为21的时候 渲染患者信息 -->
        <patient-info :record="item.msg?.consultRecord" v-if="item.msgType === 21" />
        <!-- 当msgType为31或者32的时候 渲染通知 -->
        <notify-info
          v-if="item.msgType === 31 || item.msgType === 32"
          :msgType="item.msgType"
          :content="item.msg?.content"
        />
        <!-- 当msgType为1的时候 渲染医生信息
           文字消息和图片消息都要
          -->
        <message-info
          :msg="item"
          v-if="item.msgType === 1 || item.msgType === 4"
          :type="item.msgType"
        />
        <!-- 渲染处方消息 类型为22 -->
        <prescription-info :info="item.msg?.prescription" v-if="item.msgType === 22" />
      </view>
      <!-- </view> -->
    </scroll-view>

    <!-- 发送消息 -->
    <view class="message-bar">
      <template v-if="true">
        <uni-easyinput
          :disabled="orderDetail?.status !== 3"
          :clearable="false"
          :input-border="false"
          placeholder-style="font-size: 32rpx; color: #c3c3c5;"
          placeholder="问医生"
          v-model="inputValue"
          @confirm="sendMsg"
        />
        <view class="image-button" @click="uploadImage">
          <uni-icons size="40" color="#979797" type="image"></uni-icons>
        </view>
      </template>
      <button v-else class="uni-button">咨询其它医生</button>
    </view>
  </view>
</template>

<style lang="scss">
  @import './index.scss';
</style>
